package ruifight.member.service.security;

import javax.annotation.Resource;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import ruifight.member.model.UserInfo;
import ruifight.member.model.UserInfoExample;
import ruifight.member.model.security.MyUserDetail;
import ruifight.member.service.UserInfoService;

@Service
public class SecurityProvider implements AuthenticationProvider {
	@Resource
    private UserDetailsServiceImpl userDetailsServiceImpl;
	@Resource
	private UserInfoService userInfoService;
	
    @Override
    public Authentication authenticate(Authentication authentication) {

        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        MyUserDetail userDetails = (MyUserDetail) userDetailsServiceImpl.loadUserByUsername(token.getName());
        if (userDetails == null) {
            throw new UsernameNotFoundException("找不到该用户");
        }
        UserInfo userInfo=(UserInfo) token.getCredentials();
        if(!userDetails.getPassword().equals(userInfo.getPassword()))
        {
              throw new BadCredentialsException("密码错误");
        }
        if(userInfo.getOpenId()!=null) {
        	UserInfoExample userInfoExample=new UserInfoExample();
        	userInfoExample.createCriteria()
        		.andLoginNameEqualTo(token.getName())
        		.andUserStateEqualTo(1);
        	userInfoService.updateByExampleSelective(userInfo, userInfoExample);
        	userDetails.setOpenId(userInfo.getOpenId());
        }
        return new UsernamePasswordAuthenticationToken(userDetails,userDetails.getPassword(),userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
    	
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }

}
